<template>
  <div class="editor">
    <div class="editor-header">
      <h1>调试文档编辑器</h1>
      <div class="document-actions">
        <input 
          v-model="documentTitle" 
          class="document-title" 
          placeholder="文档标题"
          @blur="saveDocument"
        />
        <button @click="saveDocument" class="save-button">保存</button>
        <button @click="goHome" class="back-button">返回首页</button>
      </div>
    </div>
    
    <div class="debug-info">
      <h3>调试信息:</h3>
      <p>路由参数 ID: {{ route.query.id }}</p>
      <p>文档 ID: {{ documentId }}</p>
      <p>用户名: {{ userName }}</p>
      <p>当前用户 ID: {{ currentUserId }}</p>
      <p>连接状态: {{ connectionStatus }}</p>
      <p>localStorage 中的用户信息: {{ localStorageUser }}</p>
    </div>
    
    <div class="connection-status" :class="connectionStatus">
      {{ connectionStatus === 'connected' ? 'Connected' : connectionStatus === 'connecting' ? 'Connecting...' : 'Disconnected' }}
    </div>
    
    <div class="editor-container" v-if="userNameSet">
      <!-- 简单的文本编辑器用于调试 -->
      <textarea 
        v-model="content" 
        @input="onEditorInput"
        rows="20"
        cols="80"
        placeholder="在此输入文档内容..."
      ></textarea>
    </div>
    
    <div class="collaboration-info" v-if="userNameSet">
      <h3>协作用户:</h3>
      
      <!-- 正在编辑的用户 -->
      <div class="user-category">
        <h4>正在编辑:</h4>
        <div v-for="user in users.filter(u => u.status === 'editing')" :key="user.id" class="user" :style="{ color: user.color }">
          {{ user.name }}
          <span v-if="user.id === currentUserId">(您)</span>
        </div>
        <div v-if="users.filter(u => u.status === 'editing').length === 0" class="no-users">暂无用户正在编辑</div>
      </div>
      
      <!-- 正在查看的用户 -->
      <div class="user-category">
        <h4>正在查看:</h4>
        <div v-for="user in users.filter(u => u.status === 'viewing')" :key="user.id" class="user" :style="{ color: user.color }">
          {{ user.name }}
          <span v-if="user.id === currentUserId">(您)</span>
        </div>
        <div v-if="users.filter(u => u.status === 'viewing').length === 0" class="no-users">暂无用户正在查看</div>
      </div>
      
      <!-- 已离开的用户 -->
      <div class="user-category">
        <h4>最近查看过:</h4>
        <div v-for="user in users.filter(u => u.status === 'left')" :key="user.id" class="user left-user" :style="{ color: user.color }">
          {{ user.name }}
        </div>
        <div v-if="users.filter(u => u.status === 'left').length === 0" class="no-users">暂无用户记录</div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'

// 路由
const router = useRouter()
const route = useRoute()

// 调试信息
const localStorageUser = ref('')

// 连接状态
const connectionStatus = ref<'disconnected' | 'connecting' | 'connected'>('disconnected')

// WebSocket连接
let socket: WebSocket | null = null

// 用户信息
const users = ref<Array<{ 
  id: string; 
  name: string; 
  color: string; 
  status: 'viewing' | 'editing' | 'left';
  lastActive: Date;
}>>([])

// 编辑器内容
const content = ref('')

// 文档信息
const documentId = ref<number | null>(null)
const documentTitle = ref('未命名文档')

// 编辑器输入事件处理
const onEditorInput = (event: Event) => {
  const target = event.target as HTMLTextAreaElement
  content.value = target.value
  
  // 发送内容更新到服务器
  if (socket && socket.readyState === WebSocket.OPEN) {
    socket.send(JSON.stringify({
      type: 'document-update',
      content: content.value,
      documentId: documentId.value
    }))
  }
}

// 从localStorage获取用户信息
const getUserInfoFromStorage = () => {
  console.log('Getting user info from localStorage')
  const user = localStorage.getItem('user')
  localStorageUser.value = user || 'null'
  console.log('Raw user data from localStorage:', user)
  
  if (user) {
    try {
      const userData = JSON.parse(user)
      console.log('Parsed user data:', userData)
      userName.value = userData.username || ''
      currentUserId.value = 'user_' + userData.id
      console.log('Set userName:', userName.value, 'currentUserId:', currentUserId.value)
    } catch (e) {
      console.error('Error parsing user data:', e)
    }
  } else {
    console.log('No user data found in localStorage')
  }
}

// 生成随机颜色
const getRandomColor = () => {
  const colors = [
    '#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#00FFFF', '#FF00FF',
    '#FFA500', '#800080', '#008000', '#000080', '#800000', '#808000'
  ]
  return colors[Math.floor(Math.random() * colors.length)]
}

// 连接到WebSocket服务器
const connect = () => {
  console.log('Attempting to connect to WebSocket server')
  console.log('Connection parameters:', { 
    userName: userName.value, 
    currentUserId: currentUserId.value, 
    documentId: documentId.value 
  })
  
  if (!userName.value || !documentId.value) {
    console.log('Missing required info for connection')
    return
  }
  
  connectionStatus.value = 'connecting'
  
  // 连接到WebSocket服务器
  socket = new WebSocket('ws://localhost:3000')
  
  socket.onopen = () => {
    console.log('Connected to WebSocket server')
    connectionStatus.value = 'connected'
    
    // 发送用户加入消息
    if (socket) {
      const userJoinMessage = {
        type: 'user-join',
        user: { 
          id: currentUserId.value, 
          name: userName.value, 
          color: getRandomColor(),
          documentId: documentId.value
        }
      }
      console.log('Sending user-join message:', userJoinMessage)
      socket.send(JSON.stringify(userJoinMessage))
    }
  }
  
  socket.onmessage = (event) => {
    console.log('Received message:', event.data)
    let data;
    try {
      data = JSON.parse(event.data);
    } catch (e) {
      console.error('Error parsing message:', event.data);
      return;
    }
    
    // 只处理当前文档的消息
    if (data.documentId !== undefined && data.documentId !== documentId.value) {
      return;
    }
    
    switch (data.type) {
      case 'document-update':
        content.value = data.content;
        break;
        
      case 'user-join':
        console.log('User joined:', data.user)
        // 添加新用户
        if (!users.value.find(u => u.id === data.user.id)) {
          users.value.push({
            ...data.user,
            status: data.user.status || 'viewing',
            lastActive: data.user.lastActive ? new Date(data.user.lastActive) : new Date()
          });
        }
        break;
        
      case 'user-update':
        // 更新用户信息
        const userIndex = users.value.findIndex(u => u.id === data.user.id);
        if (userIndex !== -1) {
          users.value[userIndex] = { 
            ...users.value[userIndex], 
            ...data.user,
            lastActive: data.user.lastActive ? new Date(data.user.lastActive) : new Date()
          };
        } else {
          users.value.push({
            ...data.user,
            status: data.user.status || 'viewing',
            lastActive: data.user.lastActive ? new Date(data.user.lastActive) : new Date()
          });
        }
        break;
        
      case 'user-leave':
        console.log('User left:', data.user)
        // 更新用户状态为已离开
        const leavingUserIndex = users.value.findIndex(u => u.id === data.user.id);
        if (leavingUserIndex !== -1) {
          users.value[leavingUserIndex].status = 'left';
          users.value[leavingUserIndex].lastActive = new Date();
        }
        break;
        
      default:
        console.log('Unknown message type:', data.type);
    }
  };
  
  socket.onclose = (event) => {
    console.log('Disconnected from WebSocket server', event)
    connectionStatus.value = 'disconnected'
  }
  
  socket.onerror = (error) => {
    console.error('WebSocket error:', error)
    connectionStatus.value = 'disconnected'
  }
}

// 加载文档
const loadDocument = async () => {
  const id = route.query.id as string
  console.log('Loading document with ID:', id)
  
  if (!id) {
    console.log('No document ID provided')
    return
  }
  
  try {
    const response = await fetch(`http://localhost:3000/api/documents/${id}`)
    const data = await response.json()
    console.log('Document load response:', data)
    
    if (response.ok) {
      documentId.value = data.document.id
      documentTitle.value = data.document.title
      content.value = data.document.content
      console.log('Document loaded:', { 
        id: documentId.value, 
        title: documentTitle.value, 
        content: content.value 
      })
    } else {
      console.error('Failed to load document:', data.error)
    }
  } catch (err) {
    console.error('Load document error:', err)
  }
}

// 保存文档
const saveDocument = async () => {
  if (!documentId.value) {
    console.log('No document ID to save')
    return
  }
  
  try {
    const response = await fetch(`http://localhost:3000/api/documents/${documentId.value}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        title: documentTitle.value,
        content: content.value
      })
    })
    
    const data = await response.json()
    
    if (response.ok) {
      console.log('Document saved successfully')
    } else {
      console.error('Failed to save document:', data.error)
    }
  } catch (err) {
    console.error('Save document error:', err)
  }
}

// 返回首页
const goHome = () => {
  router.push('/')
}

onMounted(async () => {
  console.log('DebugEditorView mounted')
  console.log('Route query:', route.query)
  
  // 从localStorage获取用户信息
  getUserInfoFromStorage()
  
  // 加载文档
  await loadDocument()
  
  // 连接到WebSocket服务器
  console.log('Checking connection conditions')
  if (userName.value && documentId.value) {
    console.log('Connecting to WebSocket server')
    connect()
  } else {
    console.log('Skipping WebSocket connection due to missing info')
    console.log('userName:', userName.value, 'documentId:', documentId.value)
  }
})

onUnmounted(() => {
  console.log('DebugEditorView unmounted')
  // 断开WebSocket连接
  if (socket) {
    if (socket.readyState === WebSocket.OPEN) {
      socket.send(JSON.stringify({
        type: 'user-leave',
        user: { id: currentUserId.value }
      }))
    }
    socket.close()
  }
})
</script>

<style scoped>
.editor {
  font-family: Arial, sans-serif;
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.document-title {
  font-size: 1.5em;
  border: none;
  outline: none;
  background: transparent;
  font-weight: bold;
}

.document-actions {
  display: flex;
  gap: 10px;
}

.save-button,
.back-button {
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  background-color: #007bff;
  color: white;
  cursor: pointer;
}

.save-button:hover,
.back-button:hover {
  background-color: #0056b3;
}

.debug-info {
  background-color: #f8f9fa;
  border: 1px solid #dee2e6;
  border-radius: 5px;
  padding: 15px;
  margin-bottom: 20px;
}

.debug-info h3 {
  margin-top: 0;
}

.debug-info p {
  margin: 5px 0;
}

.connection-status {
  padding: 10px;
  border-radius: 5px;
  margin-bottom: 20px;
  text-align: center;
}

.connection-status.connected {
  background-color: #4caf50;
  color: white;
}

.connection-status.connecting {
  background-color: #ff9800;
  color: white;
}

.connection-status.disconnected {
  background-color: #f44336;
  color: white;
}

.editor-container textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  font-family: monospace;
}

.collaboration-info {
  margin-top: 20px;
  padding: 15px;
  border: 1px solid #ddd;
  border-radius: 5px;
  background-color: #f9f9f9;
}

.collaboration-info h3 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #333;
}

.user-category {
  margin-bottom: 15px;
}

.user-category h4 {
  margin: 10px 0 5px 0;
  color: #555;
  font-size: 14px;
}

.collaboration-info .user {
  margin-bottom: 3px;
  padding: 3px 0;
}

.collaboration-info .left-user {
  opacity: 0.6;
}

.collaboration-info .no-users {
  color: #888;
  font-style: italic;
  font-size: 13px;
}
</style>
```
